package cn.kn.sys.service.impl;

import cn.kn.common.config.jwt.JWTToken;
import cn.kn.common.exception.CustomException;
import cn.kn.common.model.PageBean;
import cn.kn.common.model.PageResult;
import cn.kn.common.model.R;
import cn.kn.common.model.RCode;
import cn.kn.common.utils.CopyBean;
import cn.kn.common.utils.JWTUtils;
import cn.kn.common.utils.MD5Utils;
import cn.kn.sys.mapper.UserMapper;
import cn.kn.sys.model.User;
import cn.kn.sys.model.UserExample;
import cn.kn.sys.service.UserServic;
import cn.kn.sys.vo.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WangJiang
 * @create 2020-12-12 13:45
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends  BaseService implements UserServic {
    private final UserMapper userMapper;


    @Override
    public R list(String userName, PageBean pageBean) {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria().andIsdelEqualTo(false);
        if(!StringUtils.isEmpty(userName)){
            criteria.andNameLike("%"+userName+"%");
        }
        PageHelper.startPage(pageBean.getPage(),pageBean.getSize());
        PageInfo<User> info=new PageInfo<>(userMapper.selectByExample(userExample));
        return R.ok(new PageResult<>(info.getTotal(), CopyBean.copyBean(info.getList(), UserVo::new)));
    }

    @Override
    public R login(String username, String password) {
        String token;

        UserExample example=new UserExample();
        example.createCriteria().andIsdelEqualTo(false).andNameEqualTo(username);
        List<User> users=userMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(users)){
            throw new CustomException(RCode.USER_NOT_EXIST);
        }

        User user = users.get(0);
        String salt = user.getName();
        //秘钥为盐
        String target = MD5Utils.md5Encryption(password, salt);
        //生成Token
        token = JWTUtils.sign(username, target);
        JWTToken jwtToken = new JWTToken(token);
        try {
            SecurityUtils.getSubject().login(jwtToken);
        } catch (AuthenticationException e) {
            throw new CustomException(RCode.USER_NOT_EXIST);
        }


        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("perms",getUser().getPermissions());
        return R.ok(token,map);
    }
}
